using System;
using System.Configuration;
using Common.Core;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.Unity.Configuration;

namespace Common.Unity.Extensions.Configuration
{
	public class DependencyReferenceConfigurationElement : TypeResolvingConfigurationElement, IObjectWithKey
	{
		/// <summary>
		/// The actual <see cref="System.Type"/> object for the 
		/// type this element is registering.
		/// </summary>
		public Type Type
		{
			get { return TypeResolver.ResolveType( TypeName ); }
		}

		/// <summary>
		/// Source type to configure in the container.
		/// </summary>
		[ConfigurationProperty("type", IsRequired = true)]
		public string TypeName
		{
			get { return (string)this["type"]; }
			set { this["type"] = value; }
		}

		[ConfigurationProperty( NameName, DefaultValue = null, IsRequired = false, IsKey = false )]
		public string Name
		{
			get
			{
				string result = (string)this[NameName];
				return !string.IsNullOrEmpty( result ) ? result : null;
			}
			set { this[NameName] = value; }
		}	const string NameName = "name";

		object IObjectWithKey.Key
		{
			get
			{ 
				string result = !string.IsNullOrEmpty( Name ) ? string.Format( "{0}:{1}", Name, TypeName ) : TypeName;
				return result;
			}
		}
	}
}